package work.soho.proxy.aliyun.parts;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.*;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.utils.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DdnsWanPart extends BasePart implements IPart{
    /**
     * get client
     * @return
     */
    private IAcsClient getClient() {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", configure.getAccessKeyId(),
                configure.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    @Override
    public boolean isExist() {
        return getId() != null;
    }

    @Override
    public String getId() {
        try {
            DescribeSubDomainRecordsResponse.Record record = getDnsLanRecode();
            return record.getRecordId();
        } catch (Exception e) {
            //ignore
        }
        return null;
    }

    /**
     * 获取Dns lan ip
     *
     * @return
     */
    public DescribeSubDomainRecordsResponse.Record getDnsLanRecode() {
        try {
            DescribeSubDomainRecordsRequest describeSubDomainRecordsRequest = new DescribeSubDomainRecordsRequest();
            describeSubDomainRecordsRequest.setSubDomain("internet." + configure.getBaseDomain());
            describeSubDomainRecordsRequest.setType("A");
            DescribeSubDomainRecordsResponse describeSubDomainRecordsResponse = getClient().getAcsResponse(describeSubDomainRecordsRequest);
            if(describeSubDomainRecordsResponse.getTotalCount()>0) {
                return describeSubDomainRecordsResponse.getDomainRecords().get(0);
            }
        } catch (Exception e) {
            //ignore
        }
        return null;
    }

    @Override
    public void drop() {

    }

    /**
     * 获取局域网IP地址
     *
     * @return
     */
    public static String getWanIp() throws IOException {
        String ip = null;
        String chinaz = "http://www.net.cn/static/customercare/yourip.asp";
        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        try {
            url = new URL(chinaz);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((read = in.readLine()) != null) {
                inputLine.append(read + "\r\n");
            }
            Pattern p = Pattern.compile("\\<h2>(.*?)\\<\\/h2>");
            Matcher m = p.matcher(inputLine.toString());
            if (m.find()) {
                String ipstr = m.group(1);
                ip = ipstr;
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        if (StringUtils.isEmpty(ip)) {
            throw new RuntimeException();
        }
        return ip;
    }

    @Override
    public void create() throws AliyunPartsException, ClientException, IOException {
        //检查更新还是创建
        DescribeSubDomainRecordsResponse.Record record = getDnsLanRecode();
        if(record == null) {
            AddDomainRecordRequest addDomainRecordRequest = new AddDomainRecordRequest();
            addDomainRecordRequest.setDomainName(configure.getBaseDomain());
            addDomainRecordRequest.setRR("internet");
            addDomainRecordRequest.setType("A");
            addDomainRecordRequest.setValue(getWanIp());
            System.out.println(addDomainRecordRequest.getValue());
            AddDomainRecordResponse addDomainRecordResponse = getClient().getAcsResponse(addDomainRecordRequest);
        } else {
            String lanIp = getWanIp();
            if(!record.getValue().equals(lanIp)) {
                //更新IP地址
                UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest();
                updateDomainRecordRequest.setRecordId(record.getRecordId());
                updateDomainRecordRequest.setValue(lanIp);
                updateDomainRecordRequest.setRR("internet");
                updateDomainRecordRequest.setType("A");
                getClient().getAcsResponse(updateDomainRecordRequest);
            }
        }

    }

    @Override
    public void start() throws AliyunPartsException, ClientException, IOException {
        create();
    }

    @Override
    public void configure() throws AliyunPartsException, ClientException, IOException {
        create();
    }
}
